package com.aifund.admin.service.impl;

import com.aifund.admin.entity.form.charge.ChargePageForm;
import com.aifund.admin.entity.vo.PageResult;
import com.aifund.admin.enums.PageCodeEnum;
import com.aifund.admin.service.ChargeService;
import com.aifund.admin.service.UserService;
import com.aifund.common.dao.ChargeDao;
import com.aifund.common.entity.AiUser;
import com.aifund.common.entity.Charge;
import com.aifund.common.enums.user.ChargeEnum;
import com.aifund.common.exception.AiFundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class ChargeServiceImpl implements ChargeService {

    @Autowired
    ChargeDao chargeDao;
    @Autowired
    UserService userService;
    @Autowired
    SimpleDateFormat dayFormat;


    @Override
    public PageResult<Charge> chargeList(ChargePageForm form) {
        Specification<Charge> specification = new Specification<Charge>() {
            @Override
            public Predicate toPredicate(Root<Charge> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if(form.getHashCode() != null && !form.getHashCode().isEmpty()){
                    Predicate p1 = criteriaBuilder.like(root.get("hashCode"), "%"+form.getHashCode()+"%");
                    predicates.add(p1);
                }
                if(form.getStatus() != null){
                    Predicate p1 = criteriaBuilder.equal(root.<Integer>get("status"), form.getStatus());
                    predicates.add(p1);
                }
                if(form.getUserId() != null){
                    Predicate p1 = criteriaBuilder.equal(root.<Long>get("userId"), form.getUserId());
                    predicates.add(p1);
                }
                if(form.getNoPassReason() != null && !form.getNoPassReason().isEmpty()){
                    Predicate p1 = criteriaBuilder.like(root.get("notPassReason"), "%"+form.getNoPassReason()+"%");
                    predicates.add(p1);
                }
                if(form.getStart()!=null&&!form.getEnd().isEmpty()&&form.getStart()!=null&&!form.getEnd().isEmpty()){
                    Predicate p1 = null;
                    try {
                        p1 = criteriaBuilder.between(root.get("createTime"), dayFormat.parse(form.getStart()), dayFormat.parse(form.getEnd()));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    predicates.add(p1);
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        Sort sort = Sort.by(Sort.Direction.ASC,"createTime");
        Pageable pageable = PageRequest.of(form.getPageIndex()-1,form.getPageSize(),sort);
        Page<Charge> chargePage = chargeDao.findAll(specification,pageable);

        PageResult<Charge> pageResult = new PageResult<>();
        return pageResult.success(chargePage,form.getPageIndex()-1,form.getPageSize());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void audit(Long id, Integer status,String vertifyContext) {
        Charge charge = chargeDao.getById(id);
        if(!charge.getStatus().equals(ChargeEnum.WAIT_AUDIT.getStatus())){
            throw new AiFundException("500","已经审核过");
        }
        if(status.equals(ChargeEnum.AUDIT_NO_PASS.getStatus())){
            /**
             * 更新审核状态
             */
            charge.setStatus(status);
            charge.setNotPassReason(vertifyContext);
            chargeDao.save(charge);
        }
        if(status.equals(ChargeEnum.AUDIT_PASS.getStatus())){
            /**
             * 校验hash是否重复
             */
            Charge chargeForHash = chargeDao.getByHashCode(vertifyContext);
            if(chargeForHash!=null){
                throw new AiFundException("500","重复的HASH值");
            }
            /**
             * 更新审核状态
             */
            charge.setStatus(status);
            charge.setHashCode(vertifyContext);
            chargeDao.save(charge);
            /**
             * 给用户增加积分
             */
            AiUser aiUser = userService.getById(charge.getUserId());
            if(aiUser.getIntegration() == null){
                aiUser.setIntegration(new BigDecimal(0));
            }
            aiUser.setIntegration(aiUser.getIntegration().add(charge.getChargeNum()));
            userService.save(aiUser);
        }
    }
}
